#!/usr/bin/perl
#
#

$file_in = shift;
$file_out = shift;

sub usage {
    die "usage: $0 data.d/oix-data.dat.bz2 output.txt\n\n"; 
}


usage() unless defined $file_in;
usage() unless defined $file_out;

#system "wget \"$file_in\" -O snapshot.bz2";
open RD, "bzcat $file_in |";
open WR, "> $file_out";

$curblock = "";
$curas = -1;

$i = 0;
while(<RD>) {
    sub ignore {
        my ($line) = @_;
        print STDERR "ignoring $line\n";
    }
    chomp;
    print STDERR $i." lines..\n" if (++$i % 200000 == 0);

    # the mask is at most 2 numbers. we don't add a space at
    # the end of the regex because sometimes the input has
    # a.b.c.d/MMe.f.g.h
    unless (/^\*\s+(\d+)\.(\d+)\.(\d+)\.(\d+)\/(\d\d?+)/) {
        ignore($_);
        next;
    }
    my ($ip1, $ip2, $ip3, $ip4, $mask) = ($1, $2, $3, $4, $5);

    if (/[,{ ](\d+)\.(\d+)}? (i|e|\?)$/) {
        $as = $1*65536 + $2;
    }
    elsif (/[,{ ](\d+)}? (i|e|\?)$/) {
        $as = $1;
    }
    else {
        # parse fail
        ignore($_);
        next;
    }

    $block = sprintf("0x%x/%d", ($ip1<<24)+($ip2<<16)+($ip3<<8)+$ip4, $mask);

    if ($block eq $curblock) {
        if ($curas != $as) {
            print STDERR "conflict: block $ip1.$ip2.$ip3.$ip4/$mask was assigned to " .
                "AS $curas. Refusing to reassign to $as\n";
            next;
        }

        next;
    }

    $curblock = $block;
    $curas = $as;
    print WR "$block $as\n";
}
